import axios from 'axios'

const api =  axios.create({
    baseURL:'http://49.235.98.65:3000',
    timeout:200000,
})
// Add a request interceptor 请求拦截器
api.interceptors.request.use( config =>  {
    // Do something before request is sent 发送请求之前
    console.log('config',config)
    config.headers.user = localStorage.getItem('id') || ''
    // config.headers["user"]
    return config;
  }, function (error) {
    // Do something with request error 请求错误的处理
    return Promise.reject(error);
  });
const get = async function (url,data) {
    const response = await api.get(url,{
        params:data
    }).catch( err => {
        errorhandler(err)
    })
    return response.data;
}
const post = async function (url,data) {
    console.log('post',data)
    const response = await api.post(url,data)
    .catch( err => {
        errorhandler(err)
    })
    return response.data;
}
const put = async function (url,data) {
    console.log('put',data)
    const response = await api.put(url,data)
    .catch( err => {
        errorhandler(err)
    })
    return response.data;
}
const del = async function (url,data) {
    console.log(data)
    const response = await api.request({url, data, method:'delete'})
    .catch( err => {
        errorhandler(err)
    })
    return response;
}

//公共处理错误函数
function errorhandler(err){
    console.log('err===>',err)
    console.log('err===>',err.response.data.message);
    let msg = err&&err.response&&err.response.data&&err.response.data.message
    alert(msg)
}   

export {
    get,
    post,
    put,
    del
}